package com.thesis.config.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * web相关的配置类,需要的时候，再配置
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
//    @Resource
//    private LogInInterceptor logInInterceptor;
//    /**
//     * 添加拦截器
//     * @param registry
//     */
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(logInInterceptor)
//                .addPathPatterns("/admin/**")
//                .excludePathPatterns(
//                        "/admin/system/index/login",
//                        "/doc.html/**/**",
//                        "/swagger-resources/**",
//                        "/webjars/**",
//                        "/v2/**",
//                        "/swagger-ui.html/**",
//                        "/admin/pageElement/save");
//    }
    /**
     * 配置跨域请求
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                // SpringBoot2.4.0+ [allowedOriginPatterns]代替[allowedOrigins]
                .allowedOrigins("*")
                //.allowedOriginPatterns("*")
                // 是否允许cookie
                .allowCredentials(true)
                // 设置允许的请求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }
    /**
     * 配置类设置静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/file/**").addResourceLocations("file:./file/");
    }
    /**
     * @description 只要属性中检查出一个不符合规则的参数，立马返回，就不要再往下进行了
     * @author lanqiang
     */
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation
                .byProvider(HibernateValidator.class)
                .configure()
                .failFast(true)
                .buildValidatorFactory();
        return validatorFactory.getValidator();
    }


    @Bean
    public ObjectMapper getObjectMapper(){
        return new ObjectMapper();
    }
}
